<template>
  <div class="auth-bg">
    <div class="auth-card">
      <!-- 左侧品牌与插画 -->
      <aside class="auth-hero">
        <div class="hero-badge"><t-icon name="star" /></div>
        <h1 class="hero-title">StarVue</h1>
        <p class="hero-sub">Admin Platform</p>
        <ul class="hero-features">
          <li><t-icon name="check-circle-filled" /> 统一视觉 · 品牌主色</li>
          <li><t-icon name="check-circle-filled" /> 顺滑交互 · 轻动效</li>
          <li><t-icon name="check-circle-filled" /> 极简布局 · 高对比</li>
        </ul>
        <div class="hero-blob"></div>
      </aside>

      <!-- 右侧表单区（逻辑保持不变） -->
      <section class="auth-form">
        <header class="form-header">
          <div class="title">欢迎登录</div>
          <div class="subtitle">使用您的账号开始工作</div>
        </header>

        <!-- 已登录状态显示 -->
        <div v-if="isLoggedIn" class="logged-in-panel">
          <div class="logged-in-head">
            <div class="logged-in-avatar">
              <t-icon name="user-circle" />
            </div>
            <div class="logged-in-texts">
              <div class="logged-in-title">已登录</div>
              <div class="logged-in-sub">当前账号：<span class="strong">{{ currentUsername || '已登录用户' }}</span></div>
            </div>
          </div>
          <div class="logged-in-actions">
            <t-button theme="primary" size="large" @click="enterHome">
              进入首页
              <template #suffix><t-icon name="arrow-right" /></template>
            </t-button>
            <t-button theme="default" variant="outline" size="large" @click="switchAccount">
              切换账号
            </t-button>
          </div>

        </div>

        <t-form v-else ref="formRef" layout="vertical" preventSubmitDefault showErrorMessage labelAlign="top"
          :data="form" :rules="rules" @submit="onSubmit">
          <t-form-item label="用户名" name="username">
            <t-input v-model="form.username" placeholder="请输入用户名" size="large" clearable>
              <template #prefix-icon><t-icon name="user" /></template>
            </t-input>
          </t-form-item>

          <t-form-item label="密码" name="password">
            <t-input :type="'password'" v-model="form.password" placeholder="请输入密码" size="large" clearable>
              <template #prefix-icon><t-icon name="lock-on" /></template>
            </t-input>
          </t-form-item>

          <t-form-item label="验证码" name="captcha">
            <div class="captcha-row">
              <t-input v-model="form.captcha" size="large" name="captcha">
                <template #prefix-icon>
                  <t-icon name="barcode" />
                </template>
              </t-input>
              <div class="captcha-view" @click="loadCaptcha" :title="captchaTitle">
                <img v-if="captchaImageUrl" :src="captchaImageUrl" alt="captcha" />
                <div v-else class="captcha-placeholder">
                  <t-icon name="refresh" />
                  <span>点击获取</span>
                </div>
              </div>
            </div>
          </t-form-item>
          <t-form-item>
            <t-checkbox v-model="form.remember">记住登入</t-checkbox>
          </t-form-item>
          <t-form-item>
            <t-button class="submit-btn" theme="primary" size="large" type="submit" :loading="loading" block>
              立即登录
            </t-button>
          </t-form-item>
        </t-form>
        <t-divider dashed class="logged-in-divider">或使用其他账号登录</t-divider>
        <div class="oauth-section">
          <div class="oauth-title">
            <t-icon name="user-talk" />
            <span>第三方登录（预留）</span>
          </div>
          <div class="btns-equal">
            <t-button v-for="p in oauthProviders" :key="p.key" block theme="primary" variant="outline"
              @click="handleOAuth(p.key)">
              <template #icon>
                <t-icon :name="p.icon" :style="{ color: p.color }" />
              </template>
              <span>{{ p.name }}</span>
            </t-button>

          </div>

        </div>
      </section>
    </div>
  </div>

</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next';
import api from '@/request/api/api';
import { useAuthStore } from '@/stores/auth';
// import { useUserStore } from '@/stores/user';
// const user = useUserStore();

const router = useRouter();
const auth = useAuthStore();
const loading = ref(false);
const isLoggedIn = ref(false);
const currentUsername = ref('');
const enterHome = () => router.push('/');
const switchAccount = () => {
  const dialog = DialogPlugin.confirm({
    header: '切换账号',
    body: '确认要切换其他账号吗？这将清除当前登录状态。',
    theme: 'warning',
    confirmBtn: { content: '确认', theme: 'danger' },
    cancelBtn: '取消',
    closeOnOverlayClick: true,
    onConfirm: () => {
      auth.clear();
      isLoggedIn.value = false;
      currentUsername.value = '';
      MessagePlugin.success('已切换账号');
      dialog.destroy();
    },
    onCancel: () => {
      dialog.destroy();
    },
    onClose: () => {
      dialog.destroy();
    },
  });
};

const rules = {
  username: [
    { required: true, message: '请输入用户名', type: 'error', trigger: 'blur' },
    { min: 2, message: '用户名长度需大于 1 个字符', type: 'warning', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', type: 'error', trigger: 'blur' },
    { min: 6, message: '密码长度至少 6 位', type: 'warning', trigger: 'blur' },
  ],
  captcha: [
    { required: true, message: '请输入验证码', type: 'error', trigger: 'blur' },
    { len: 4, message: '验证码为 4 位', type: 'warning', trigger: 'change' },
  ],
};

const form = reactive({
  username: '',
  password: '',
  captcha: '',
  remember: false,
});

const captchaImageUrl = ref('');
const captchaKey = ref('');
const captchaTitle = ref('点击刷新验证码');

// 与 axios 实例的 baseURL 对齐
const apiBase = (import.meta.env && (import.meta.env.VUE_APP_API_URL || import.meta.env.VITE_APP_API_URL)) || '/api';
const joinUrl = (base, path) => {
  if (!path) return '';
  const b = String(base || '').replace(/\/+$/, '');
  const p = String(path || '').replace(/^\/+/, '');
  return `${b}/${p}`;
};

function normalizeCaptchaPayload(res) {
  // 兼容常见结构：{ data: { image_url, captcha_key } } 或 { image, key } 等
  const payload = res?.data ?? res ?? {}; 
  const imageUrl = payload.image_url || payload.image || payload.img || payload.captcha_image || '';
  const key = payload.captcha_key || payload.key || payload.uuid || payload.id || '';
  // 图片链接优先使用完整URL，其次拼接 baseURL
  const image = imageUrl
    ? (/^https?:\/\//i.test(imageUrl) ? imageUrl : joinUrl(apiBase, imageUrl))
    : '';
  return { image, key };
}

const loadCaptcha = async () => {
  try {
    captchaTitle.value = '加载中...';
    const res = await api.getCaptcha();
    const { image, key } = normalizeCaptchaPayload(res);
    captchaImageUrl.value = image || '';
    captchaKey.value = key || '';
    captchaTitle.value = '点击刷新验证码';
  } catch (e) {
    captchaTitle.value = '加载失败，点击重试';
    MessagePlugin.error('验证码获取失败');
  }
};

const onSubmit = async () => {
  if (!form.username || !form.password) {
    MessagePlugin.warning('请输入用户名和密码');
    return;
  }
  if (!form.captcha) {
    MessagePlugin.warning('请输入验证码');
    return;
  }
  loading.value = true;
  try {
    // 储存userinfo


    // 根据“记住”选项切换存储类型
    auth.switchStorageType(form.remember ? 'local' : 'session');
    // 根据后端约定可兼容多种字段命名
    const base = { username: form.username, password: form.password };
    const captchaPayload = captchaKey.value
      ? { captcha_value: form.captcha, captcha_key: captchaKey.value }
      : { captcha_value: form.captcha };
    const res = await api.login({ ...base, ...captchaPayload });
    // 保存用户名到持久化（后端返回或表单值）
    try {
      const uname = res?.data?.username || form.username || '';
      auth.setUsername(uname);
      currentUsername.value = uname;
    } catch (_) {}
    isLoggedIn.value = true;
    // 记录用户名，便于显示已登录状态
    MessagePlugin.success('登录成功');
    router.push('/');
  } catch (e) {
    MessagePlugin.error(e?.message || '登录失败，请检查信息');
    // 刷新验证码以防止复用
    // loadCaptcha();
  } finally {
    loading.value = false;
  }
};

// 第三方登录（使用上方已声明的 apiBase/joinUrl）
const oauthProviders = [
  { key: 'wechat', name: '微信', icon: 'logo-wechat-stroke', color: '#07c160' },
  { key: 'github', name: 'GitHub', icon: 'logo-github', color: '#333' },
  // { key: 'gitee', name: 'Gitee', icon: 'logo-github', color: '#C71D23' },
  // { key: 'google', name: 'Google', icon: 'logo-google', color: '#EA4335' },
];
const handleOAuth = (providerKey) => {
  console.log(providerKey);
  MessagePlugin.warning('暂未实现第三方登录');


};

// 默认不请求验证码，手动点击再获取
// 登录检测：若已有 access token 或 refresh token，则显示登录状态区
onMounted(() => {
  console.log('当前存储类型:', auth.getCurrentStorageType());
  console.log('access token:', auth.access);
  console.log('refresh token:', auth.refresh);

  // 检查是否已登录（access token 或 refresh token 存在即可）
  if (auth.access || auth.refresh) {
    isLoggedIn.value = true;
    currentUsername.value = auth.username || '';
  }
});
</script>

<style scoped>
/* 背景层 */
.auth-bg {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 56px 24px;
  background:
    radial-gradient(1200px 700px at 10% 15%, var(--td-brand-color-light) 0%, transparent 60%),
    radial-gradient(900px 500px at 90% 85%, var(--td-brand-color-focus) 0%, transparent 60%),
    linear-gradient(135deg, var(--td-brand-color-light), var(--td-brand-color));
}

/* 双栏大卡片 */
.auth-card {
  width: 100%;
  max-width: 1040px;
  display: grid;
  grid-template-columns: 1.2fr 1fr;
  border-radius: 20px;
  overflow: hidden;
  background: transparent;
  box-shadow: 0 28px 68px rgba(0, 0, 0, .12), 0 6px 20px rgba(0, 0, 0, .06);
}

/* 左侧品牌插画面板 */
.auth-hero {
  position: relative;
  padding: 56px 44px;
  background: linear-gradient(135deg, var(--td-brand-color-hover), var(--td-brand-color));
  color: var(--td-text-color-anti);
}

.hero-badge {
  width: 76px;
  height: 76px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: color-mix(in oklab, var(--td-text-color-anti) 20%, transparent);
  margin-bottom: 18px;
  box-shadow: inset 0 0 0 1px color-mix(in oklab, var(--td-text-color-anti) 25%, transparent);
}

.btns-equal {
  display: grid;
  grid-auto-flow: column;
  /* 根据子元素个数生成列 */
  grid-auto-columns: 1fr;
  /* 每列 1fr，自动等分 */
  gap: var(--td-comp-margin-s, 12px);
}

.hero-title {
  font-size: 38px;
  font-weight: 800;
}

.hero-sub {
  opacity: .9;
  margin-bottom: 18px;
}

.hero-features {
  list-style: none;
  padding: 0;
  margin: 0;
  display: grid;
  gap: 12px;
}

.hero-features li {
  display: flex;
  align-items: center;
  gap: 8px;
  opacity: .96;
}

.hero-blob {
  position: absolute;
  right: -80px;
  bottom: -80px;
  width: 380px;
  height: 380px;
  background: radial-gradient(circle at 30% 30%, color-mix(in oklab, var(--td-text-color-anti) 35%, transparent), transparent 60%);
  filter: blur(8px);
  opacity: .6;
  pointer-events: none;
}

/* 右侧表单面板 */
.auth-form {
  background: color-mix(in srgb, var(--td-bg-color-container) 95%, transparent);
  padding: 44px 40px 36px;
}

.form-header {
  text-align: left;
  margin-bottom: 20px;
}

.logo-surface {
  width: 60px;
  height: 60px;
  border-radius: 16px;
  margin-bottom: 10px;
  background: var(--td-bg-color-secondarycontainer);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--td-brand-color);
}

.title {
  font-size: 24px;
  font-weight: 700;
  color: var(--td-text-color-primary);
}

.subtitle {
  color: var(--td-text-color-secondary);
  margin-top: 2px;
}

/* 表单统一放大 */
:deep(.t-form__label) {
  color: var(--td-text-color-secondary);
  font-weight: 600;
  font-size: 14px;
}

:deep(.t-form--label-top .t-form__label) {
  margin-bottom: 8px;
}

:deep(.t-input__wrap) {
  height: 52px;
  border-radius: 14px;
  background: var(--td-bg-color-secondarycontainer);
  transition: .2s;
}

:deep(.t-input__inner) {
  font-size: 16px;
}

:deep(.t-input__wrap:hover) {
  border-color: var(--td-brand-color-hover);
}

:deep(.t-input__wrap.t-is-focused) {
  border-color: var(--td-brand-color);
  box-shadow: 0 0 0 3px var(--td-brand-color-light);
  background: var(--td-bg-color-container);
}

/* 验证码 */
.captcha-row {
  display: grid;
  grid-template-columns: 1fr 140px;
  gap: 16px;
  align-items: center;
}

.captcha-view {
  width: 140px;
  height: 52px;
  border-radius: 14px;
  border: 1px solid var(--td-component-border);
  background: var(--td-bg-color-secondarycontainer);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: .18s;
}

.captcha-view:hover {
  transform: translateY(-1px);
  border-color: var(--td-brand-color);
  box-shadow: 0 0 0 3px var(--td-brand-color-light);
}

.captcha-view img {
  width: 120px;
  height: 48px;
  object-fit: contain;
  border-radius: 10px;
}

.captcha-placeholder {
  color: var(--td-text-color-secondary);
  display: flex;
  align-items: center;
  gap: 6px;
}

.submit-btn {
  margin-top: 10px;
  height: 54px;
  border-radius: 14px;
  background: linear-gradient(135deg, var(--td-brand-color), var(--td-brand-color-active));
  box-shadow: 0 8px 22px rgba(0, 0, 0, .08), 0 2px 8px rgba(0, 0, 0, .06);
  transition: .18s;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 28px rgba(0, 0, 0, .12), 0 4px 10px rgba(0, 0, 0, .08);
}

/* 已登录块 */
.logged-in-panel {
  background: linear-gradient(180deg, rgba(var(--td-brand-color-rgb), 0.04), rgba(var(--td-brand-color-rgb), 0.02));
  border: 1px solid rgba(var(--td-brand-color-rgb), 0.12);
  border-radius: 14px;
  padding: 14px 16px;
  margin-bottom: 12px;
}

.logged-in-head {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logged-in-avatar {
  width: 44px;
  height: 44px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(var(--td-brand-color-rgb), 0.12);
  color: var(--td-brand-color);
  font-size: 22px;
}

.logged-in-texts {
  line-height: 1.2;
}

.logged-in-title {
  font-weight: 700;
  color: var(--td-text-color-primary);
}

.logged-in-sub {
  color: var(--td-text-color-secondary);
}

.logged-in-sub .strong {
  color: var(--td-text-color-primary);
  font-weight: 600;
}

.logged-in-actions {
  display: flex;
  gap: 10px;
  margin-top: 12px;
}

.logged-in-divider {
  margin: 8px 0;
}

/* 第三方登录（预留） */
.oauth-section {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.oauth-title {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  color: var(--td-text-color-secondary);
  font-weight: 600;
}











@media (max-width: 1040px) {
  .auth-card {
    max-width: 880px;
  }
}

@media (max-width: 960px) {
  .auth-card {
    grid-template-columns: 1fr;
    max-width: 720px;
  }

  .auth-hero {
    padding: 36px 28px;
  }

  .auth-form {
    padding: 28px 24px;
  }
}
</style>
